package com.dora.optimistic.lock.controller;

import com.dora.redis.domian.Result;
import com.dora.optimistic.lock.entity.User;
import com.dora.optimistic.lock.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 *
 * @author Clarence
 * @date 2024/02/25
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 根据用户ID查询用户信息接口
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable("id") Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return Result.ok(user);
        } else {
            return Result.fail();
        }
    }

    // 更新用户信息接口
    @PostMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        try {
            boolean success = userService.updateUser(user);
            if (success) {
                return Result.ok("User updated successfully.");
            } else {
                return Result.fail("Failed to update user.");
            }
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }
}
